package com.cy.pj.common.web.config;


import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {






    @Bean
    public SessionManager sessionManager(){
        DefaultWebSessionManager sessionManager =
                new DefaultWebSessionManager();
        //session的超时时间
        sessionManager.setGlobalSessionTimeout(20000);
        //sessionManager.setGlobalSessionTemeout(2*60*1000)
        //删除无效session
        sessionManager.setDeleteInvalidSessions(true);
        //当客户端cookie被禁用是否要设置url重写
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }


    /**
     * 会话session记住我
     * @return
     */
    @Bean
    public RememberMeManager rememberMeManager(){
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setMaxAge(7*27*60*60);//设置cookie的生命周期
        rememberMeManager.setCookie(cookie);
        rememberMeManager.setCipherKey(Base64.decode("SwnFSIIM+ib9FgTHZKbKzg=="));
        return rememberMeManager;
    }

    //生成加密键
//    @Bean
//    public void testGeneratorKey() throws NoSuchMethodException, NoSuchAlgorithmException {
//        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//        SecretKey secretKey = keyGenerator.generateKey();
//        String key = Base64.encodeToString(secretKey.getEncoded());
//        System.out.println(key);
//    }

    /**
     * 配置授权缓存管理器,默认应用的缓存是shiro框架内置的缓存对象
     * 缓存实现就是一个map
     * @return
     */
    @Bean
    protected CacheManager shiroCacheManager(){
        return  new MemoryConstrainedCacheManager();
    }
}
